package com.aiti.ai.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.ai.entity.ShowPremuEnterpriseEntity;
import com.aiti.ai.service.ShowPremuEnterpriseService;
import com.aiti.ai.service.ai.MessageAssistant;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * description:
 * auth fcb
 * date 2025-03-22 17:00
 **/
@Slf4j
public class ExeTaskRunnable implements Runnable{

    private CountDownLatch latch;

    private ShowPremuEnterpriseService showPremuEnterpriseService;

    private int limit;

    private int offset;

    private MessageAssistant newFieldAssistant;

    public ExeTaskRunnable(CountDownLatch latch, int limit, int offset, ShowPremuEnterpriseService showPremuEnterpriseService, MessageAssistant newFieldAssistant) {
        this.limit = limit;
        this.offset = offset;
        this.latch = latch;
        this.showPremuEnterpriseService = showPremuEnterpriseService;
        this.newFieldAssistant = newFieldAssistant;
    }

    @Override
    public void run() {
        List<ShowPremuEnterpriseEntity> dataList = this.showPremuEnterpriseService.pageQuery(limit, offset);
        if(CollectionUtil.isEmpty(dataList)) {
            this.latch.countDown();
            return;
        }
        List<String> ids = new ArrayList<>();
        for (ShowPremuEnterpriseEntity enterpriseEntity : dataList) {
            try {
                String aiText = this.newFieldAssistant.dealExistField(enterpriseEntity.getCompanyName());
                ShowPremuEnterpriseEntity aiResultObj = this.getObjByJson(aiText);
                if (aiResultObj == null) {
                    ids.add(enterpriseEntity.getId());
                    continue;
                }
                this.merge(enterpriseEntity, aiResultObj);
                enterpriseEntity.setDealFlag(1);
                this.showPremuEnterpriseService.updateById(enterpriseEntity);
            }catch (Exception e) {
                log.error("AI生成企业数据异常：{}", ExceptionUtil.stacktraceToString(e));
            }
        }
        if(CollectionUtil.isNotEmpty(ids)) {
            log.error("AI生成企业数据异常的id列表：{}", ids);
        }
        this.latch.countDown();
    }

    private ShowPremuEnterpriseEntity getObjByJson(String json) {
        if(StrUtil.isEmpty(json)) {
            return null;
        }
        String s = json;
        try {
            if(json.contains("```json") && json.contains("```")) {
                s = json.substring(json.indexOf("```json") + 7, json.lastIndexOf("```"));
            }
            ShowPremuEnterpriseEntity bean = JSONUtil.toBean(s, ShowPremuEnterpriseEntity.class);
            return bean;
        }catch (Exception e) {
            log.error("AI模型返回数据：{}", json);
            log.error("AI模型返回数据处理异常：{}", ExceptionUtil.stacktraceToString(e));
            return null;
        }
    }

    public <T> void merge(T a, T b) throws IllegalAccessException {
        Class<?> clazz = a.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if ("id".equals(field.getName()) || "serialVersionUID".equals(field.getName()) || "dealFlag".equals(field.getName())){
                continue;
            }

            field.setAccessible(true);
            Object aValue = field.get(a);
            String v = (String) aValue;
            if (StrUtil.isNotEmpty(v)) {
                field.set(a, null);
            } else {
                Object bValue = field.get(b);
                field.set(a, bValue);
            }
        }
    }

}
